<template>
  <div class="order-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>订单详情</span>
          <el-button @click="handleBack">返回列表</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 订单状态 -->
        <div class="status-section">
          <el-steps :active="getStatusStep(orderInfo.status)" finish-status="success">
            <el-step title="待付款" />
            <el-step title="待发货" />
            <el-step title="待收货" />
            <el-step title="已完成" />
          </el-steps>
        </div>

        <!-- 订单信息 -->
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(orderInfo.status)">
              {{ getStatusText(orderInfo.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(orderInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ formatDate(orderInfo.payTime) }}</el-descriptions-item>
          <el-descriptions-item label="发货时间">{{ formatDate(orderInfo.shipTime) }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ formatDate(orderInfo.completeTime) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 商品信息 -->
        <div class="section-title">商品信息</div>
        <el-table :data="orderItems" border style="width: 100%">
          <el-table-column label="商品图片" width="100">
            <template #default="{ row }">
              <el-image
                :src="row.itemImage"
                :preview-src-list="[row.itemImage]"
                fit="cover"
                class="goods-image"
              />
            </template>
          </el-table-column>
          <el-table-column prop="itemName" label="商品名称" min-width="200" />
          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">
              ¥{{ formatNumber(row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ formatNumber(row.totalPrice) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 收货信息 -->
        <div class="section-title">收货信息</div>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="收货人">{{ orderInfo.recipientName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderInfo.recipientPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">
            {{ formatAddress(orderInfo) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 支付信息 -->
        <div class="section-title">支付信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="支付方式">
            {{ formatPaymentMethod(orderInfo.paymentMethod) }}
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="orderInfo.paymentStatus === 1 ? 'success' : 'warning'">
              {{ orderInfo.paymentStatus === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品总额">
            ¥{{ formatNumber(orderInfo.itemAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="运费">
            ¥{{ formatNumber(orderInfo.freightAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="优惠金额">
            ¥{{ formatNumber(orderInfo.discountAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
            ¥{{ formatNumber(orderInfo.payAmount) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 物流信息 -->
        <template v-if="orderInfo.status >= 2">
          <div class="section-title">物流信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="物流公司">
              {{ formatLogisticsCompany(orderInfo.logistics?.company) }}
            </el-descriptions-item>
            <el-descriptions-item label="物流单号">
              {{ orderInfo.logistics?.trackingNo }}
            </el-descriptions-item>
          </el-descriptions>
        </template>

        <!-- 备注信息 -->
        <div class="section-title">备注信息</div>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单备注">
            {{ orderInfo.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 操作按钮 -->
        <div class="operation-buttons">
          <el-button
            v-if="orderInfo.status === 1"
            type="primary"
            @click="handleShip"
          >
            发货
          </el-button>
          <el-button
            v-if="orderInfo.status === 0"
            type="danger"
            @click="handleCancel"
          >
            取消订单
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="shipLoading">
            确认发货
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, jiangShipOrder, jiangCancelOrder } from '@/api/order'
import service from '@/utils/request'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipFormRef = ref(null)

// 订单信息
const orderInfo = ref({})
const orderItems = ref([])

// 发货表单
const shipForm = ref({
  company: '',
  trackingNo: ''
})

// 发货表单验证规则
const shipRules = {
  company: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 格式化数字
const formatNumber = (num) => {
  const n = Number(num)
  if (isNaN(n)) return '0.00'
  return n.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  const d = new Date(date)
  if (isNaN(d.getTime())) return '暂无'
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化地址
const formatAddress = (address) => {
  if (!address) return '无'
  return `${address.province}${address.city}${address.district}${address.addressDetail}`
}

// 格式化支付方式
const formatPaymentMethod = (method) => {
  const methods = {
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付',
    'BANK': '银行卡'
  }
  return methods[method] || method
}

// 格式化物流公司
const formatLogisticsCompany = (company) => {
  const companies = {
    'SF': '顺丰速运',
    'ZTO': '中通快递',
    'YTO': '圆通速递',
    'YD': '韵达快递',
    'STO': '申通快递'
  }
  return companies[company] || company
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '已完成',
    4: '已取消'
  }
  return texts[status] || '未知'
}

// 获取状态步骤
const getStatusStep = (status) => {
  if (status === 4) return 0
  return status + 1
}

// 加载订单详情
const loadOrderDetail = async () => {
  loading.value = true
  try {
    const res = await getOrder(route.params.id)
    orderInfo.value = res.order
    orderItems.value = res.orderItems || []
  } catch (error) {
    console.error('加载订单详情失败：', error)
    ElMessage.error('加载订单详情失败')
  } finally {
    loading.value = false
  }
}

// 返回列表
const handleBack = () => {
  router.back()
}

// 发货
const handleShip = () => {
  shipForm.value = {
    company: '',
    trackingNo: ''
  }
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = async () => {
  if (!shipFormRef.value) return
  
  try {
    await shipFormRef.value.validate()
    
    shipLoading.value = true
    await jiangShipOrder(route.params.id, shipForm.value)
    
    ElMessage.success('发货成功')
    shipDialogVisible.value = false
    loadOrderDetail()
  } catch (error) {
    if (error === 'cancel') return
    console.error('发货失败：', error)
    ElMessage.error('发货失败，请重试')
  } finally {
    shipLoading.value = false
  }
}

// 取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await jiangCancelOrder(route.params.id)
    ElMessage.success('订单已取消')
    loadOrderDetail()
  } catch (error) {
    if (error === 'cancel') return
    console.error('取消订单失败：', error)
    ElMessage.error('取消订单失败，请重试')
  }
}

const handleCommand = (command) => {
  if (command === 'logout') {
    // 退出登录逻辑
    // 比如 userStore.logout() 或清除token等
    // router.push('/login')
  } else if (command === 'profile') {
    // 跳转到个人信息页
    // router.push('/jiang/profile')
  } else if (command === 'password') {
    // 跳转到修改密码页
    // router.push('/jiang/password')
  }
}

const currentRoute = computed(() => {
  // 优先显示meta.title，没有就显示路径
  return route.meta?.title || route.name || route.path
})

onMounted(() => {
  loadOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail {
  .detail-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .status-section {
    margin-bottom: 30px;
    padding: 20px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
  }

  .section-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: bold;
    color: var(--el-text-color-primary);
  }

  .goods-image {
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }

  .operation-buttons {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    gap: 20px;
  }
}
</style>
